from selenium import webdriver
import time
import traceback


class AutoClick(object):
    def __init__(self):
        pass


    def run2(keyword, url):
        chromeOptions = webdriver.ChromeOptions()
        chromeOptions.add_argument('headless')
        chromeOptions.add_argument('--cast-initial-screen-width=1080')
        chromeOptions.add_argument('--cast-initial-screen-height=1960')
        # chromeOptions.add_argument("--proxy-server=http://182.111.109.227:4273")
        chromeOptions.add_argument('disable-infobars')
        chromeOptions.add_argument('--window-size=1366,768')
        ua = 'user-agent="Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36"'
        chromeOptions.add_argument(ua)
        driver = webdriver.Chrome(chrome_options=chromeOptions)
        driver.set_window_size(375, 667)
        driver.get("http://www.baidu.com")
        driver.find_element_by_xpath('//*[@id="index-kw"]').send_keys(keyword)
        # 点击百度一下
        time.sleep(3)
        driver.find_element_by_xpath('//button[@id="index-bn"]').click()
        flag = False
        page = 0
        while True:
            time.sleep(3)
            a_link_list = driver.find_elements_by_xpath('//article//span[starts-with(@class, "c-showurl")]')
            for i in range(len(a_link_list)):
                # //span[starts-with(@class, "c-showurl")]
                try:
                    tmp = driver.find_elements_by_xpath('//span[starts-with(@class, "c-showurl")]')[i].text.replace('/', '')
                    print(tmp)
                    if url in tmp:
                        print("OK")
                        flag = True
                        driver.find_elements_by_xpath('//span[starts-with(@class, "c-showurl")]/../../../../..')[i].click()
                        time.sleep(500)
                        driver.close()
                        return
                except IndexError:
                    pass
            page += 1
            print(page)
            time.sleep(5)
            if not flag:
                try:
                    if page == 1:
                        driver.execute_script("document.querySelector('#page-controller > div > a').click()")
                    else:
                        driver.execute_script("document.querySelector('#page-controller > div > div.new-pagenav-right > a').click()")
                except:
                    print("此关键词无搜索结果")
                    break

            print("当前位置：第{}页，无搜索结果".format(page))


    def run1(keyword, url):
        chromeOptions = webdriver.ChromeOptions()
        # chromeOptions.add_argument("--proxy-server=http://115.214.76.130:4270")
        # chromeOptions.add_argument('disable-infobars')
        ua = 'user-agent="Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C28 Safari/419.3"'
        chromeOptions.add_argument(ua)
        driver = webdriver.Chrome(chrome_options=chromeOptions)
        # driver.set_window_size(375, 667)
        driver.get("http://www.baidu.com")
        driver.find_element_by_xpath('//*[@id="kw"]').send_keys(keyword)
        # 点击百度一下
        driver.find_element_by_xpath('//input[@id="su"]').click()
        flag = False
        page = 0
        while True:
            time.sleep(3)
            a_link_list = driver.find_elements_by_xpath('//h3[starts-with(@class,"t")]')
            for i in range(len(a_link_list)):
                try:
                    tmp = driver.find_elements_by_xpath('//h3[starts-with(@class,"t")]/../div[@class="f13"]/a[1]')[i].text.replace('/', '')
                    print(tmp)
                    if url in tmp:
                        print("OK")
                        flag = True
                        driver.find_elements_by_xpath('//h3[starts-with(@class,"t")]/../div[@class="f13"]/a[1]')[i].click()
                        time.sleep(9999)
                        driver.close()
                        return
                except IndexError:
                    pass
            page += 1
            print(page)
            if not flag:
                try:
                    if page == 1:
                        driver.find_element_by_xpath('//a[@class="n"]').click()
                    else:
                        driver.find_element_by_xpath('//a[@class="n"][2]').click()
                except:
                    print("此关键词无搜索结果")
                    break
            print("当前位置：第{}页，无搜索结果".format(page))


if __name__ == '__main__':
    AutoClick.run1("Realme3PRO18999卢比", 'zq7z.com')
